package com.kylin.module.community.business;

/*
import java.text.SimpleDateFormat;
import java.text.ParseException;
*/
import java.io.IOException;
import java.util.Date;
import java.util.List;

import com.kylin.common.Constants;
import com.kylin.common.exception.BusinessException;

import com.kylin.common.paginate.DisplayPage;
import com.kylin.common.paginate.PageManager;
import com.kylin.common.paginate.Paging;
import com.kylin.common.util.Config;
import com.kylin.common.util.FileOperater;

import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.hibernate.TransactionDAO;
import com.kylin.module.community.forms.MemberForm;
import com.kylin.module.community.orm.Member;
import com.kylin.module.community.orm.MemberDAO;
import com.kylin.module.community.orm.FriendslistDAO;

import com.kylin.module.user.orm.User;
import com.kylin.module.user.orm.UserDAO;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.common.dict.orm.Dict;

import org.apache.log4j.Logger;
import org.apache.struts.upload.FormFile;


public class MemberBlogic {
	
	private int psgeSize = 15;
	protected static Logger log = Logger.getLogger(MemberBlogic.class);

	public Paging show(MemberForm form, Integer limitstart, Integer limit){
		Paging page = new Paging();
		MemberDAO fdao = new  MemberDAO();
		
		page.setTotal(fdao.getTotal(form));
		page.setList(fdao.getList(limitstart, limit,form));
		page.setStart(limitstart);
		page.setLimit(limit);
		
		return page;		
	}		
	
	public Member addMember(MemberForm form)throws BusinessException{
		//TransactionDAO txDao = new TransactionDAO();
		//Member cat = new Member();
		//List same = txDao.findByProperty(User.class, "username",form.getUsername());
		//if(same != null && same.size() > 0)
		//	throw new BusinessException("已经存在相同的用户名 "+form.getUsername());
		try{
			/*
			 * new user 
			 */
			//log.info(form.toString());
			User user = new User();
			user.setActive(new Short("1"));
			user.setCountry(form.getCountry());
			user.setCreatedon(new Date());
			user.setUserrole(new Short ("0") );  // 0 for member, 1 for company
			user.setLanguage(form.getLanguage());
			user.setUsername(form.getUsername());
			user.setName(form.getName());
			user.setEmail(form.getEmail());
			user.setPassword(form.getPassword());
			BaseHibernateDAO.save(user);
			//txDao.startTansction();
			//BaseHibernateDAO.save(user);
			//user = (User)txDao.saveRtObj(user);
			
			/*
			 * new member
			 */
			Member member = new Member();
			member.setActive(new Short("1"));
			member.setCity(form.getCity());
			//member.setEmail(form.getEmail());
			member.setCreatedon(new Date());
			member.setIntroduce(form.getIntroduce());
			if (form.getInterestid().intValue()!=0  && form.getInterestid()!= null) {
				try{
					Dict interest = (Dict)BaseHibernateDAO.findById(Dict.class, form.getInterestid());
					member.setInterest(interest);
				}
				catch(Exception e){
					log.info(e.toString());
				}
			}
			member.setCountry(form.getCountry());
			member.setTargetlang(form.getTargetlang());
			member.setLanguage(form.getLanguage());
			member.setSex(form.getSex());
			member.setHits(new Integer(0));			
			member.setBirthday(form.getDateBirthday()); // helper methord in form
			member.setUser(user);
			BaseHibernateDAO.save(member);
			//txDao.save(member);
			//txDao.commitTansction();
			
			return member;
			
		}catch(BusinessException e){
			log.info(e.toString());
			//txDao.rollbackTansction();
			throw new BusinessException("msg.manage.saveMember.fail",e);
		}
	}

	public User loginUser(String username, String password){
		
		UserDAO udao = new UserDAO();		
		User user =  udao.login(username, password);	
		
		return user;
		
	}
	/*
	 * 
	 * 
	 */
	public void updateMember(MemberForm form)throws BusinessException{
		//TransactionDAO txDao = new TransactionDAO();
		
		try{
			log.info("member update");
			//txDao.startTansction();			
			Member member = (Member)BaseHibernateDAO.findById(Member.class, form.getId());
			
			//member.setEmail(form.getEmail());
			member.setCountry(form.getCountry());
			member.setCity(form.getCity());

			if (form.getInterestid().intValue()!=0 && form.getInterestid()!= null) {
				Dict interest = (Dict)BaseHibernateDAO.findById(Dict.class, form.getInterestid());
				member.setInterest(interest);
			}			
			
			member.setIntroduce(form.getIntroduce());
			member.setLanguage(form.getLanguage());
			member.setTargetlang(form.getTargetlang());
			//member.setPhone(form.getPhone());
			
			if (!"".equals(form.getImgFile()) && form.getImgFile() != null ){
			
				String imgurl = null;// member.getImgurl();
				log.info(form.toString());
				
					if (member.getImgurl() == null || "".equals(member.getImgurl()) ){				
							imgurl = uploadImage("member", form.getImgFile(), null);				
					}
					else{
						
						log.info(">>>>>>>>>>>>>>>>>> "+member.getImgurl());
						imgurl = 	uploadImage("member", form.getImgFile(), member.getImgurl());
					}
				// log.info(">>> imgfile >>>: "+form.getImgFile()); ???
				log.info(">>>>>>>>>>>>: "+imgurl);
				if ( imgurl == null && !"".equals(member.getImgurl())){
					imgurl = member.getImgurl();
				}
				member.setImgurl(imgurl);
			}
			else{
				log.info("not empty");
			}
			
			member.setSex(form.getSex());
			member.setHits( new Integer(member.getHits().intValue()+1) );			
			member.setBirthday(form.getDateBirthday());
			member.setLastupdatedon(new Date());
			BaseHibernateDAO.update(member);
			//txDao.saveOrUpdate(member);
			//txDao.commitTansction();
			
		}catch(BusinessException e){
			//txDao.rollbackTansction();
			throw new BusinessException("member update fail",e);
		}
	}

	
	private String uploadImage(String flag,FormFile formFile,String oldFile) throws BusinessException{
	    log.debug("flag="+flag+" ,formFile="+formFile+" ,oldFile="+oldFile);
			String imgUrl = null;
			if (formFile != null 
					&& formFile.getFileSize() > 0
					&& formFile.getFileName() != null
					&& !formFile.getFileName() .equals("")) {
	log.debug(" FileSize()="+formFile.getFileSize() + ", FileName()="+formFile.getFileName());			
				if(formFile.getFileSize() > Config.uploadMaxSize*1024)
					throw new BusinessException("上传文件尺寸最大不能超过 "+Config.uploadMaxSize+" KB");
				try{
					if(oldFile == null || oldFile.equals("")){
						if("member".equals(flag))
							imgUrl = FileOperater.saveUploadFile(Constants.IMG_MEMBER,
											formFile.getInputStream(), 
											formFile.getFileName());
					}else{
						if("member".equals(flag))
							imgUrl = FileOperater.updateUploadFile(Constants.IMG_MEMBER,
									formFile.getInputStream(), 
									formFile.getFileName(),
									oldFile);
					}
				}catch(IOException e){
					throw new BusinessException("不能读取上传的文件："+e,e);
				}
			}
			return imgUrl;
		}
	
	
	public List getLastReg(){
		log.info("get last 10 registers");
		MemberDAO mdao = new MemberDAO();
		return mdao.findLastReg();
	}
 
	public List list(Long id){
		try{
		User user = (User)BaseHibernateDAO.findById(User.class, id);
		log.info("get last 10 registers"+user.getUsername());
		FriendslistDAO fdao = new FriendslistDAO();
		return fdao.list(user);
		}
		catch(BusinessException e){
			return null;
		}
	}

	public Member getMemberByUserId(Long uid) throws BusinessException {
		Member member = null;
		try{
			User user = (User)BaseHibernateDAO.findById(User.class, uid);
			MemberDAO mdao = new MemberDAO();
			member =  mdao.findme(user);
			
		}
		catch(BusinessException e){
			throw new BusinessException("msg.manage.getMember.fail",e);
		}
		
		return member;
	}	
	
	
	public Member getMemberByUser(User user) throws BusinessException {
		MemberDAO mdao = new MemberDAO();
		Member member =  mdao.findme(user);
		return member;
	}
	
	public DisplayPage getMemberList(int pageNum, CriteriaInfo cinfo) throws BusinessException {
		log.info("search cat page " + pageNum);
		DisplayPage page = PageManager.getDisplayPage(psgeSize, pageNum, cinfo);
		return page;
	}
	
}
